<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\controller;

use app\common\library\wechat\WxPay;
use app\common\exception\BaseException;

use app\api\model\wxapp\Setting as WxappSettingModel;
use app\common\enum\order\PayType as OrderPayTypeEnum;
use EasyWeChat\Factory;
use app\common\library\helper;
use app\common\enum\OrderType as OrderTypeEnum;

/**
 * 支付成功异步通知接口
 * Class Notify
 * @package app\api\controller
 */
class Notify
{
    /**
     * 支付成功异步通知(微信小程序-微信支付)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxpay()
    {
        // 微信支付组件：验证异步通知
        $WxPay = new WxPay();
        $WxPay->notify();
    }

    public function wxpayh5()
    {
        $storeId = getStoreId();
        $c = WxappSettingModel::getWxappConfig($storeId);
        $config = [
            'app_id' => $c['app_id'],
            'mch_id' => $c['mchid'],
            'key' => $c['apikey'],
        ];
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            log_record($message);
            // 实例化订单模型
            $orderNo = $message['out_trade_no'];
            $attach = helper::jsonDecode($message['attach']);
            // 判断订单类型返回对应的订单模型
            $model = $this->modelClass[$attach['order_type']];
            $model = new $model($orderNo);
            // 订单信息
            $order = $model->getOrderInfo();
            if(empty($order)){
                return '订单不存在';
            }
            // 订单支付成功业务处理
            $status = $model->onPaySuccess(OrderPayTypeEnum::WECHATH5, $message);
            if ($status == false) {
                return $model->getError();
            }
            return true;
        });

        return $response->send();
    }
}
